package com.googlecode.olabs.common.client.contact.formats;

import java.util.Collection;
import java.util.List;

import com.googlecode.olabs.common.client.contact.ContactException;
import com.googlecode.olabs.common.client.contact.field.EMailField;
import com.googlecode.olabs.common.client.contact.field.Field;
import com.googlecode.olabs.common.client.contact.field.FormattedNameField;
import com.googlecode.olabs.common.client.contact.field.IdField;
import com.googlecode.olabs.common.client.contact.field.NameField;
import com.googlecode.olabs.common.client.contact.field.OrganizationField;
import com.googlecode.olabs.common.client.contact.field.TelephoneField;
import com.googlecode.olabs.common.client.contact.field.UnsupportedField;
import com.googlecode.olabs.common.client.contact.field.UrlField;

public abstract class AbstractParser implements Parser {

	public static final Field[] ALL_FIELDS = new Field[] { new EMailField(),
			new FormattedNameField(), new IdField(), new NameField(),
			new OrganizationField(), new TelephoneField(), new UrlField() };
	public static final Field GENERIC_FIELD = new UnsupportedField();

	protected Field createField(String type, Collection<String> subTypes,
			List<String> value) throws ContactException {
		String upperType = type.toUpperCase();
		for (Field field : ALL_FIELDS) {
			if (upperType.equals(field.getType())) {
				Field result = createEmptyClone(field);
				populateField(result, subTypes, value);
				return result;
			}
		}
		if (upperType.startsWith(UnsupportedField.TYPE_PREFIX)) {
			return createField(upperType.substring(UnsupportedField.TYPE_PREFIX
					.length()), subTypes, value);
		} else {
			UnsupportedField result = new UnsupportedField();
			result.setType(upperType);
			populateField(result, subTypes, value);
			return result;
		}
	}

	private Field createEmptyClone(Field toClone) {
		Field cloned = (Field) toClone.clone();
		cloned.clearSubTypes();
		return cloned;
	}

	private Field populateField(Field field, Collection<String> subTypes,
			List<String> value) throws ContactException {
		for (String subType : subTypes) {
			field.addSubType(subType);
		}
		field.setValue(value);
		return field;
	}
}
